import React, { useEffect, useState, useCallback } from "react";
import {
  Form,
  Input,
  Select,
  Button,
  message,
  Radio,
  DatePicker,
  TimePicker,
} from "antd";
// import moment from "moment";
// import {
//   savePlan,
//   updatePlan,
//   queryTriggerType,
//   queryProductType,
//   queryCallType,
//   listCustomerEvent,
// } from "../../utils/service";
import { DEFAULT_CONFIG } from "../../../helper/const";
// import CirclePeople from "../circlePeople";
// import CycleTime from "../cycleTime";
// import SearchSelect from "../searchSelect";
// import "./index.scss";
// import locale from "antd/es/date-picker/locale/zh_CN";

const { Option } = Select;


const DrawerForm = Form.create({
  name: "addOrUpdateForm",
})((props) => {
  const {
    form,
    backfillValues = {},
    handelCloseDrawer,
    visible,
    setLoading,
  } = props;
  const [ radioText, setRadioText ] =useState('');

  /** 表单是否编辑 */
  // const isEdit = !!backfillValues?.id;
  const { getFieldDecorator, validateFieldsAndScroll, getFieldValue } = form;
  // // const dataType = getFieldValue('dataType')
  // const [triggerTypeList, setTriggerTypeList] = useState([]);
  // const [productTypeList, setProductTypeList] = useState([]);
  // const [callTypeList, setCallTypeList] = useState([]);

  // useEffect(() => {
  //   queryTriggerType({})
  //     .then((res) => {
  //       if (res.success) {
  //         const { data = [] } = res;
  //         console.log(data, "daaaaa");
  //         getValueCode(data, setTriggerTypeList);
  //       }
  //     })
  //     .catch((err) => {});
  //   queryProductType({})
  //     .then((res) => {
  //       if (res.success) {
  //         const { data = [] } = res;
  //         getValueCode(data, setProductTypeList);
  //       }
  //     })
  //     .catch((err) => {});
  //   queryCallType({})
  //     .then((res) => {
  //       if (res.success) {
  //         const { data = [] } = res;
  //         getValueCode(data, setCallTypeList);
  //       }
  //     })
  //     .catch((err) => {});
  // }, []);

  // const getValueCode = (data = [], setData) => {
  //   const arr = [];
  //   data.forEach((item) => {
  //     arr.push({
  //       label: item.name,
  //       value: item.code,
  //     });
  //   });
  //   setData(arr);
  // };

  // /** 表单提交 */
  // const handleSubmit = (e) => {
  //   e.preventDefault();
  //   validateFieldsAndScroll(async (err, values) => {
  //     if (!err) {
  //       try {
  //         setLoading?.(true);
  //         const {
  //           cycleConfig = {},
  //           scheduleTime,
  //           dataType,
  //           groupId,
  //           ids,
  //           scheduleType,
  //           sql,
  //           cronExpression,
  //           triggerType,
  //         } = values;
  //         const timeFormat =
  //           scheduleType == "fixed_time" ? "YYYY-MM-DD HH:mm:ss" : "HH:mm:ss";
  //         const { textContent } = sql || {};
  //         const params = {
  //           ...values,
  //           dataSource: JSON.stringify({
  //             dataType,
  //             groupId,
  //             ids,
  //             sql: textContent,
  //           }),
  //           triggerConfig: JSON.stringify({
  //             scheduleType,
  //             scheduleTime: scheduleTime ? scheduleTime.format(timeFormat) : "",
  //             cronExpression,
  //             ...cycleConfig,
  //           }),
  //         };
  //         delete params.cycleConfig;
  //         delete params.dataType;
  //         delete params.groupId;
  //         delete params.ids;
  //         delete params.sql;
  //         delete params.scheduleTime;
  //         delete params.scheduleType;
  //         delete params.triggerOppType;
  //         delete params.cronExpression;
  //         triggerType !== "schedule" && delete params.triggerConfig;
  //         triggerType === "old_default" && delete params.dataSource;
  //         // console.log(params, 'params')
  //         // return
  //         const { success, message: msg } = await (isEdit
  //           ? updatePlan(params)
  //           : savePlan(params));
  //         if (success) {
  //           message.success(isEdit ? "修改成功" : "新增成功");
  //           handelCloseDrawer?.();
  //         } else {
  //           message.error("操作失败:" + msg);
  //         }
  //         setLoading?.(false);
  //       } catch (error) {
  //         setLoading?.(false);
  //         message.error("操作失败:" + error);
  //         console.error(error);
  //       }
  //     }
  //   });
  // };

  /** 渲染表单项 */
  const renderItem = (item, value, dataType) => {
    const { placeholder = "", name } = item;
    switch (item?.uiType) {
      case "textArea":
        return (
          <Input.TextArea
            placeholder={placeholder || "请输入" + name}
            disabled={item?.editAble === false}
            allowClear={allowClear}
            autoSize={{
              minRows: 4,
              maxRows: 10,
            }}
          />
        );
      case "select":
        return (
          <Select
            placeholder={placeholder || "请选择" + name}
            disabled={item?.editAble === false}
            // allowClear={allowClear}
          >
            {(item?.enum || [])?.map((option) => (
              <Option key={option?.value} value={option?.value}>
                {option?.label}
              </Option>
            ))}
          </Select>
        );
      case "radio":
        return (
          <Radio.Group onChange={(e)=>setRadioText(e.target.value)}  >
            {(item?.enum || [])?.map((option) => 
            {
              const {value, label,radioComponent,radioComponentPlaceholder} = option||{};
              return (
                <Radio value={value}>
                  <>
                   
                    {radioComponent && (
                      <DatePicker.MonthPicker disabled={radioText!==value} placeholder={'请选择月份'}></DatePicker.MonthPicker>
                    )}
                    {label}
                  </>
                </Radio>
              );}
            )}
           
          </Radio.Group>
        );
      case "circlePeople":
        return <CirclePeople {...item} />;
      case "datePicker":
        return (
          <DatePicker
            format="YYYY-MM-DD HH:mm:ss"
            showTime
            locale={{
              ...locale,
              lang: {
                ...locale.lang,
                shortWeekDays: ["日", "一", "二", "三", "四", "五", "六"],
                shortMonths: [
                  "一",
                  "二",
                  "三",
                  "四",
                  "五",
                  "六",
                  "七",
                  "八",
                  "九",
                  "十",
                  "十一",
                  "十二",
                ],
              },
            }}
            placeholder={placeholder || "请选择" + name}
          />
        );
      case "cycleTime":
        return (
          <CycleTime
            {...item}
            placeholder={placeholder || "请选择" + name}
            defaultValue={value}
          />
        );
      case "timePicker":
        return (
          <TimePicker
            format="HH:mm:ss"
            placeholder={placeholder || "请选择" + name}
          />
        );
      // case "searchSelect":
      //   return (
      //     <SearchSelect
      //       disabled={item?.editAble === false}
      //       dataType={dataType}
      //       placeholder={placeholder || "清输入并选择" + name}
      //       searchService={searchService}
      //     />
      //   );
      default:
        return (
          <Input
            placeholder={placeholder || "请输入" + name}
            disabled={item?.editAble === false}
          />
        );
    }
  };

  function handleFormItem(item, getFieldValue, renderFormItem) {
    if (
      !item ||
      !typeof getFieldValue == "function" ||
      !typeof renderFormItem == "function"
    ) {
      return null;
    }
    const { relyFn, requiredFn, setEnum } = item || {};
    const dataType = getFieldValue("dataType");
    const triggerType = getFieldValue("triggerType");
    if (typeof requiredFn == "function") {
      const required = requiredFn(getFieldValue);
      item.required = required;
    }
    if (typeof setEnum == "function") {
      item.enum = setEnum(getFieldValue);
    }
    if (typeof relyFn == "function") {
      const isShow = relyFn(getFieldValue);
      return (isShow && renderFormItem(item, dataType)) || null;
    }
    return renderFormItem(item, dataType);
  }

  const setRenderFields = () => {
    return DEFAULT_CONFIG.map((item) => {
      if (item.key === "bizScene") {
        item.enum = callTypeList;
      }
      if (item.key === "productType") {
        item.enum = productTypeList;
      }
      if (item.key === "triggerType") {
        item.enum = triggerTypeList;
      }
      return item;
    });
  };

  const renderForm = useCallback((data) => {
    return (
      Array.isArray(data) &&
      data.map((item, index) => {
        return handleFormItem(item, getFieldValue, renderFormItem);
      })
    );
  }, []);

  /** 渲染form字段 */
  const renderFormItem = (item, dataType) => {
    let backfillValuesData = { ...backfillValues };

    return (
      <Form.Item
        label={item?.name}
        // extra={item?.tips}
        required={item?.required}
      >
        {getFieldDecorator(item?.key, {
          initialValue:
            backfillValuesData?.[item.key] || item?.defaultValue || "",
          rules: [
            {
              required: item?.required,
              ...(item.rules
                ? item.rules
                : { message: item.message || `请输入${item?.name}` }),
            },
          ],
        })(renderItem(item, backfillValuesData?.[item.key], dataType))}
      </Form.Item>
    );
  };



  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 19 },
    },
  };

  // if (!visible) return null;

  return (
    <div className="drawerForm">
      <Form
        {...formItemLayout}
        // className="drawerForm_mainForm"
        // onSubmit={handleSubmit}
      >
        {DEFAULT_CONFIG.map((item) => {
          const { formItemName = "-", formItemConfig = [] } = item || {};
          return (
            <>
              <div className="item-drawer-form-title">{formItemName}</div>
              {renderForm(formItemConfig)}
            </>
          );
        })}

        <div className="drawerForm_footer">
          <Button style={{ marginRight: 8 }}>取消</Button>
          <Button
          // type="primary"
          // htmlType="submit"
          // data-trace-click="clk-crm-open-form-list-submit"
          // data-logmeta={`isEdit=${isEdit}`}
          >
            提交
          </Button>
        </div>
      </Form>
    </div>
  );
});

export default DrawerForm;
